<template>
  <div class="sdy-good-list">
    <SdyHeader title="啥都有~商品列表" back>sousuo</SdyHeader>

    <van-card v-for="item in goodsList" :num="2" :price="item.originprice" :desc="item.desc" :title="item.proname"
      :thumb="item.img1">
      <template #footer>
        <van-button size="mini" round type="warning" @click="ToDetail(item.proid)">查看详情</van-button>
        <van-button size="mini" color="linear-gradient(to right, #ff6034, #ee0a24)" icon="cart-o" round
          @click="addCartHandler(item.proid)">加入购物车</van-button>
      </template>
    </van-card>
  </div>
</template>

<script setup lang="ts">

import { useRoute, type RouteLocationNormalizedLoaded } from 'vue-router'
import { useRouter, type Router } from 'vue-router';
import { Toast } from "vant";
import { ref, onMounted } from 'vue';
// 导入相关TS 条件
import type { MyHotItem } from '@/config/interface';
import { searchListApi } from '@/api/goods';
// 导入购物车相关的接口
import { addCartApi } from '@/api/Cart'
const $route: RouteLocationNormalizedLoaded = useRoute()
const $router: Router = useRouter()
// 准备一个函数，拿到搜索带过来的信息储存在 localStorage 内
const setLocalStorage = ((text: string): void => {
  const historyList: string[] = JSON.parse(window.localStorage.getItem('history') as string) || []
  // 把text 追加倒数组内 然后重新储存回 locastorage 内
  // 如果历史记录内有和这个消息了 不需要插入了
  const res: boolean = historyList.indexOf(text) !== -1
  // console.log(res);
  // 如果 res === true 说明有
  // 什么都不做
  if (res) return

  // 代码执行到这里 说明历史记录没有过该信息
  historyList.push(text)
  // 再次把最新的数组存储到 localStorage 内
  window.localStorage.setItem('history', JSON.stringify(historyList))
})

//1.根据携带过来的关键字 来请求数据
// 准被一个数据，表示当前第几页
const count = ref<number>(1)

// 准备一个数组来渲染页面
const goodsList = ref<MyHotItem[]>([])
const getGoodsList = async (text: string) => {
  const res = await searchListApi(text, count.value)
  // console.log(res.data);
  goodsList.value = res.data

}

// 跳转到商品详情页
const ToDetail = (id: string) => {
  // console.log(`查看 id 为 ${ id } 的商品详情`)
  // 直接跳转路由, 携带参数即可
  $router.push({ path: '/detail', query: { proid: id } })

}

// 加入购物车
const addCartHandler = async(id:string) => {
  // 获取用户id 和 token
  const userid = window.localStorage.getItem('userid')
  const token = window.localStorage.getItem('token')
  // 非空验证 
  if (!userid ||!token) {
    Toast({
      message: '请登录后，添加购物车',
   })
  //  setTimeout(()=>{
  //    $router.push('/login')
  //  },3000)
   return
  }
   //代码执行到这里，说明登录成功
  //  发送请求
  const res= await addCartApi( userid ,id)
  console.log(res);
  if(((res as unknown) as { code: string }).code === '200')  Toast({
      message: '加入购物车成功',
   })
  

}
onMounted(() => {
  // console.log($route);
  const searchText = $route.query.search
  searchText && setLocalStorage(searchText as string);
  searchText && getGoodsList(searchText as string);

})

</script>

<style scoped lang="scss">
.sdy-good-list {
  height: 100%;
  overflow-y: auto;
}
</style>